<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <!-- COMPLETE: "按时完成",
        LATE_COMPLETE: "逾期完成",
        LATE_PENDING_PROCESS: "逾期待处理",
        PENDING_PROCESS: "待处理",
        VOIDED: "已作废" -->
      <TableData :config="table_config" :tableThead="tableThead" :dataList="dataList" :loading="loading"
        @selection-change="selectionChange">
        <template v-slot:lookView="{ row }"><span class="pointer primary" @click="clickView(row)">点击查看</span></template>
        <template v-slot:workTime="{ row }">{{ row.workStartTime + '至' + row.workEndTime }}</template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="handleSizeChange" :size="size"   @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <LookView @closeDialog="closeDialog" :dialogVisible="viewFlag" :dataInfo="lookViewData">
      </LookView>
      <AddEdit :title="'作业记录'" @closeDialog="closeDialog" :batchList="batchList" :materialList="materialList"
        :facilityList="facilityList" :workType="searchFormData.workType" :addEditFlag="addEditFlag"
        :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from '@/components/Pagination';
import SearchForm from '@/components/SearchForm';
import TableData from '@/components/TableData';
import BtnSlot from '@/components/BtnSlot';
import EnumSlot from '@/components/EnumSlot';
import LookView from './components/lookView.vue';
import AddEdit from './components/addEdit.vue';
import jobTaskManagement from '@/api/jobManagment/jobTaskManagement';
import batch from '@/api/batch/batchManagement';
import facilityManagement from '@/api/digtalOperation/facilityManagement.js';
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage"; // 物料

export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit, LookView },
  data() {
    return {
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      viewFlag: false,
      addEditFlag: 'add',
      viewList: [],
      formData: {},
      btnList: ['add', 'delete'],
      workStatus: 'COMPLETE',
      searchFormData: {
        workType: 'FEEDING',
        workStatus: 'COMPLETE',
        status: 'ENABLE'
      },
      page: 1,
      size:10,
      total: 100,
      selectIndex: 0,
      // workStatus: {
      //   COMPLETE: "按时完成",
      //   LATE_COMPLETE: "逾期完成",
      //   LATE_PENDING_PROCESS: "逾期待处理",
      //   PENDING_PROCESS: "待处理",
      //   VOIDED: "已作废"
      // },
      workType: {
        CHANGE_WATER: "换水作业",
        HANGING_NET: "吊网作业",
        EXPOSED_NET: "漏网作业",
        FEEDING: "饲喂作业",
        DISINFECTION_WATER: '消杀作业'
      },
      enumList: [{
        label: "饲喂作业",
        type: 'FEEDING'
      },
      {
        label: "吊网作业",
        type: 'HANGING_NET'
      },
      {
        label: "漏网作业",
        type: 'EXPOSED_NET'
      },
      {
        label: "消杀作业",
        type: "DISINFECTION_WATER"
      },
      {
        label: "换水作业",
        type: 'CHANGE_WATER'
      }],
      dataList: [],
      lookViewData: {},
      tableThead: [
        { isShow: true, label: '养殖设施', prop: 'facilityName', minWidth: '120px' },
        { isShow: true, label: '批次名称', prop: 'batchName', minWidth: '120px' },
        { isShow: true, label: '作业人', prop: 'staffName' },
        { isShow: true, label: '作业时间', slotName: 'workTime', minWidth: '200px' },
        { isShow: true, label: '查看详情', slotName: 'lookView' },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: '操作',
          width: '200',
          cols: [
            {
              label: '编 辑',
              type: 'primary',
              flag: 'edit',
              handleRow: this.handleRow
            },
            {
              label: '删 除',
              type: 'danger',
              flag: 'delete',
              handleRow: this.handleRow
            }
          ]
        },
      },
      formItemList: [
        {
          label: '养殖设施',
          type: 'select',
          selectOptions: [],
          param: 'facilityId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }, {
          label: '批次名称',
          type: 'select',
          selectOptions: [],
          param: 'batchId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }, {
          label: '作业人',
          type: 'select',
          selectOptions: [],
          param: 'staffName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        }, {
          label: '作业开始日期',
          type: 'datetimerange',
          param: 'firstDate',
          multiple: false,
          isShow: true
        }, {
          label: '作业结束日期',
          type: 'datetimerange',
          param: 'secondDate',
          multiple: false,
          isShow: true
        }
      ],
      materialList: [],
      batchList: [],
      facilityList: []
    }
  },
  computed: {
    person() {
      return this.$store.state.initData.person || [];
    },
  },
  mounted() {
    this.initData();
    this.queryPageByCondition();
  },
  methods: {
    async initData() {
      let { data: materialList } = await materialApi.getqueryList({});
      let { data: batchList } = await batch.queryByCondition({ batchType: 'BREEDING' })
      let { data: facilityList } = await facilityManagement.getFacilityListByConditionAll({
        breedType: sessionStorage.breedType
      });
      //药品
      this.materialList = materialList;
      //饲料类型集合
      let materialTypeList = ['1083401155740872704', '6216514614165446114', '1160159772231639040', '1160159777575182336', '1160159780939014144', '1160159784701304832']
      this.materialList = this.materialList.filter(data => {
        console.log(materialTypeList.includes(data.materialTypeNo))
        return materialTypeList.includes(data.materialTypeNo)
      })
      this.batchList = batchList || [];
      this.facilityList = facilityList || [];
      this.setFormOptions()
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('facilityId') !== -1) {
          console.log(this.facilityList)
          let selectOptions = this.facilityList.map(data => {
            return {
              text: data.facilityName, value: data.facilityId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('batchId') !== -1) {
          let selectOptions = this.batchList.map(data => {
            return {
              text: data.batchName, value: data.batchId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param == 'staffName') {
          let selectOptions = this.person.map(data => {
            return {
              text: data.person.name, value: data.person.name
            }
          })
          item.defaultSelect = this.searchFormData[item.param]
          item.selectOptions = selectOptions;
        };
      });
      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    clickView(row) {
      this.viewFlag = true
      this.lookViewData = { ...row }
      console.log(row)
    },
    handleClick(tab, event) {
      console.log(tab, event, this.workStatus);
      this.queryPageByCondition()
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData,
          workStatus: this.workStatus,
          taskCreate: "MANUAL_WORK"
        }
      }
      jobTaskManagement.queryPageByCondition(params).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    search(data) {
      this.page = 1;
      let secondStartDate, secondEndDate, firstStartDate, firstEndDate = null
      if (data.secondDate && data.secondDate.length == 2) {
        secondStartDate = `${data.secondDate[0]} 00:00:00`;
        secondEndDate = `${data.secondDate[1]} 23:59:59`;
      }
      if (data.firstDate && data.firstDate.length == 2) {
        firstStartDate = `${data.firstDate[0]} 00:00:00`;
        firstEndDate = `${data.firstDate[1]} 23:59:59`;
      }
      this.searchFormData = {
        ...this.searchFormData,
        ...data,
        secondStartDate,
        secondEndDate,
        firstStartDate,
        firstEndDate
      };
      this.queryPageByCondition();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    delList(deleteList = [], key = 'workTaskId') {
      let list = []
      deleteList.forEach(item => {
        list.push(item[key])
      })
      console.log(list)
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await jobTaskManagement.delList(list);
        if (res.code == 1) {
          this.$message.success(res.msg || '删除成功');
          this.queryPageByCondition();
        } else {
          this.$message.warning(res.msg || '删除失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 操作方法
    handleRow(rowData, item) {
      console.log(rowData, item);
      if (item.flag == 'delete') { //删除
        this.delList([rowData])
      } else if (item.flag == 'edit') { //作废
        this.dialogVisible = true;
        this.formData = JSON.parse(JSON.stringify(rowData))
      }
      this.addEditFlag = item.flag
    },
    //作废
    taskCanCel(id) {
      this.$confirm('您确定要作废该条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await jobTaskManagement.taskCanCel(id);
        if (res.code == 1) {
          this.$message.success('操作成功');
        } else {
          this.$message.warning(res.msg || '操作失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      } else if (flag == 'delete') {
        if (this.selectList.length > 0) {
          this.delList(this.selectList)
        } else {
          this.$message.warning('请先选择表单数据项后再删除！')
        }
      }
      this.addEditFlag = flag
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //处理
    taskProcess(id) {
      this.$confirm('您确定要处理该条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await jobTaskManagement.taskProcess(id);
        if (res.code == 1) {
          this.$message.success('操作成功');
        } else {
          this.$message.warning(res.msg || '操作失败');
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      });
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      let { data, index } = enumInfo;
      this.selectIndex = index || 0;
      this.searchFormData.workType = data.type;
      this.queryPageByCondition();
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.viewFlag = false;
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped>
.pointer {
  cursor: pointer;
}
</style>